/**
 * git tag操作
 * */
import fs from "node:fs";
import path from "node:path";
import { exec } from "node:child_process";

const packagePath = process.cwd()
const packageJson = JSON.parse(fs.readFileSync(path.join(packagePath, '/package.json'), 'utf-8'))

const tagName = `${packageJson.name}-v${packageJson.version}`

exec('git tag', async (err, stdout) => {
    if (err) {
        console.log('获取tag标签失败', err);
        return
    }
    console.log('获取tag标签:', stdout ? stdout : '暂无标签');
    const tagList = stdout.split('\n');
    if (tagList.includes(tagName)) await deleteTag(tagName)
    const { err: createErr } = await exec(`git tag ${tagName}`)
    if(createErr) {
        console.log('创建tag标签失败', err);
        return
    }
    console.log(`标签${tagName}创建成功`);
    const { err:pushErr } = await exec(`git push origin ${tagName}`)
    if(pushErr) {
        console.log('推送tag标签失败', err);
    } else {
        console.log(`标签${tagName}推送成功`);
        await exec(`git tag -d ${tagName}`)
    }
})

/**
 * @param {String} tagName 标签名称
 * */
async function deleteTag(tagName) {
   try {
       if (!tagName) return
       await exec(`git tag -d ${tagName}`)
       await exec(`git push origin :refs/tags/${tagName}`)
       console.log(`删除tag：${tagName}标签成功`);
   } catch (err) {
       console.log(err);
       console.log('创建tag标签失败', err);
   }
}
